package com.joshua.ticket.utils;

import java.util.*;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.joshua.userservice.models.Menu;

@Component
@Scope(value = "singleton")
public class MenuCache {

	@Autowired
	public SessionFactory sessionFactory;
	
	private Map<String, Menu> menuMap = null;

	public Map<String, Menu> getMenuMap() {
		if (menuMap == null) {
			menuMap = new HashMap<String, Menu>();
			initMenuData();
		}
		return menuMap;
	}

	public void setMenuMap(Map<String, Menu> menuMap) {
		this.menuMap = menuMap;
	}

	public MenuCache() {
	}

	public void initMenuData() {
		try {
			Session session = sessionFactory.openSession();
			Transaction tx = session.beginTransaction();
			List menus = session.createQuery("from Menu").list();

			for (Object oMenu : menus) {
				Menu menu = (Menu) oMenu;
				menuMap.put(menu.getCode(), menu);
			}

			tx.commit();
			session.close();

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			System.out.println(ex.getCause().getMessage());
		}
	}

}
